package com.wfg.nettydemo.io.nio.channel;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author wufagang
 * @description
 * @date 2024年03月19日 19:52
 */
public class NIOFileChannel03 {
    public static void main(String[] args) throws Exception {
//        channelToChannel();
        channelToChannel2();
    }
    /**
     * channel to channel 通过transferFrom 完成
     */
    public static void channelToChannel2() throws Exception {
        FileInputStream inputStream = new FileInputStream("1.txt");
        FileChannel inputStreamChannel = inputStream.getChannel();
        FileOutputStream outputStream = new FileOutputStream("2.txt");
        FileChannel outputStreamChannel = outputStream.getChannel();

        //outputStreamChannel.transferFrom(inputStreamChannel,0, inputStreamChannel.size());
        inputStreamChannel.transferTo(0,inputStreamChannel.size(),outputStreamChannel);
        inputStream.close();
        inputStreamChannel.close();
        outputStream.close();
        outputStreamChannel.close();
    }
    /**
     * channel to channel 通过ByteBuffer 完成
     */
    public static void channelToChannel()throws Exception{
        FileInputStream inputStream = new FileInputStream("1.txt");
        FileChannel inputStreamChannel = inputStream.getChannel();
        FileOutputStream outputStream = new FileOutputStream("2.txt");
        FileChannel outputStreamChannel = outputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(512);

        while (true){
            byteBuffer.clear();
            int read = inputStreamChannel.read(byteBuffer);
            System.out.println("read = " + read);
            if(read == -1){
                break;
            }
            byteBuffer.flip();
            outputStreamChannel.write(byteBuffer);
        }
        inputStream.close();
        outputStream.close();
    }
}
